/**
 *
 * @description: 回复的业务代码
 * @author: junyong.hong
 * @createTime: 2018/10/10
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
const { resolve } = require('path')
const commonMenu = require('./menu')
const config = require('../config/config')
const api = require('../app/api/index')

const help = '亲爱的，欢迎关注科幻电影世界\n' +
    '回复 1 ~ 3，测试文字回复\n' +
    '回复 4，测试图文回复\n' +
    '回复 首页，进入电影首页\n' +
    '回复 电影名字，查询电影信息\n' +
    '点击帮助，获取帮助信息\n' +
    '某些功能订阅号无权限，如网页授权\n' +
    '回复 语音，查询电影信息\n' +
    '也可以点击 <a href="' + config.wechat.baseUrl + '/wechat/movie">语音查电影</a>'


exports.reply = async (ctx, next) => {
    // 在wechat-lib/middleawre.js上已经挂载
    const message = ctx.weixin

    // 每个人与服务器交互都是一个用户（要放在这里，放在外面是通用的token）
    let mp = require('./index')
    let client = mp.getWechat()

    // 语音查电影
    if (message.MsgType === 'voice') {
        // 微信对语音的解析
        let content = message.Recognition
        let reply = ''

        let movies = await api.movie.searchByKeyword(content)
        reply = []

        if (!movies || movies.length === 0) {
            let catData = await api.movie.findMoviesByCat(content)
            if (catData) {
                movies = catData.movies
            }
        }

        if (!movies || movies.length === 0) {
            movies = await api.movie.searchByDouban(content)
        }

        if (!movies || movies.length) {
            reply = []
            movies = movies.splice(0, 4)

            movies.forEach(movie => {
                reply.push({
                    title: movie.title,
                    description: movie.title,
                    picUrl: 'http://img2.mukewang.com/5abe468b0001664107390741-160-160.jpg',
                    url: config.baseUrl + '/movie/' + movie._id
                })
            })
        } else {
            reply = '没有查询到与 ' + content + ' 相关的电影，换个名字试试'
        }

        ctx.body = reply
    }
    else if (message.MsgType === 'image') {
        console.log('图片' + message.PicUrl)
    }
    else if (message.MsgType === 'event') {
        let reply = ''

        if (message.Event === 'subscribe'){
            reply = '欢迎订阅' + '! 扫码参数' + message.EventKey + '_' + message.ticket
        }
        else if (message.Event === 'unsubscribe') {
            reply = '无情取消订阅'
        }
        else if (message.Event === 'SCAN') {
            console.log('关注后扫二维码' + '! 扫码参数' + message.EventKey + '_' + message.ticket)
        }
        else if (message.Event === 'LOCATION') {         // 获取用户经纬度信息
            console.log(`您上报的位置是${message.Latitude} - ${message.Longitude} - ${message.Precision}`)
        }
        else if(message.Event === 'CLICK') {
            // 点击帮助，回复引导文案
            if (message.EventKey === 'help') {
                reply = help
            }
            // 最热门
            else if (message.EventKey === 'movie_hot') {
                // -1倒序 4查询4条数据
                let movies = await api.movie.findHotMovies(-1, 4)
                reply = []

                movies.forEach(movie => {
                    reply.push({
                        title: movie.title,
                        description: movie.summary,
                        picUrl: 'http://img2.mukewang.com/5abe468b0001664107390741-160-160.jpg',
                        url: config.baseUrl + '/movie/' + movie._id
                    })
                })
            }
            // 最冷门
            else if (message.EventKey === 'movie_cold') {
                let movies = await api.movie.findHotMovies(1, 4)
                reply = []

                movies.forEach(movie => {
                    reply.push({
                        title: movie.title,
                        description: movie.summary,
                        picUrl: 'http://img2.mukewang.com/5abe468b0001664107390741-160-160.jpg',
                        url: config.baseUrl + '/movie/' + movie._id
                    })
                })
            }
            // 科幻
            else if (message.EventKey === 'movie_sci') {
                let catData = await api.movie.findMoviesByCat('科幻')
                let movies = catData.movies || []
                reply = []

                movies.forEach(movie => {
                    reply.push({
                        title: movie.title,
                        description: movie.summary,
                        picUrl: 'http://img2.mukewang.com/5abe468b0001664107390741-160-160.jpg',
                        url: config.baseUrl + '/movie/' + movie._id
                    })
                })
            }
            // 爱情
            else if (message.EventKey === 'movie_love') {
                let catData = await api.movie.findMoviesByCat('爱情')
                let movies = catData.movies || []
                reply = []

                movies.forEach(movie => {
                    reply.push({
                        title: movie.title,
                        description: movie.summary,
                        picUrl: 'http://img2.mukewang.com/5abe468b0001664107390741-160-160.jpg',
                        url: config.baseUrl + '/movie/' + movie._id
                    })
                })
            }

            console.log('你点击了菜单的： ' + message.EventKey)
        }
        else if(message.Event === 'VIEW') {
            console.log('你点击了菜单链接： ' + message.EventKey + ' ' + message.MenuId)
        }
        else if (message.Event === 'scancode_push') {
            console.log('你扫码了： ' + message.ScanCodeInfo.ScanType + ' ' + message.ScanCodeInfo.ScanResult)
        }
        else if (message.Event === 'scancode_waitmsg') {  // 扫码推事件且弹出“消息接收中”提示款的事件推送
            console.log('你扫码了： ' + message.ScanCodeInfo.ScanType + ' ' + message.ScanCodeInfo.ScanResult)
        }
        else if (message.Event === 'pic_sysphoto') {
            console.log('系统拍照： ' + message.SendPicsInfo.Count + ' ' + JSON.stringify(message.SendPicsInfo.PicList))
        }
        else if (message.Event === 'pic_photo_or_album') {
            console.log('拍照或者相册： ' + message.SendPicsInfo.Count + ' ' + JSON.stringify(message.SendPicsInfo.PicList))
        }
        else if (message.Event === 'pic_weixin') {
            console.log('微信相册发图： ' + message.SendPicsInfo.Count + ' ' + JSON.stringify(message.SendPicsInfo.PicList))
        }
        else if (message.Event === 'location_select') {
            console.log('地理位置： ' + JSON.stringify(message.SendLocationInfo))
        }

        ctx.body = reply
    }
    else if (message.MsgType === 'text') {        // 判断类型（纯文本类型）

        // 消息字段名
        let content = message.Content
        // 默认文案
        let reply = '你说的 ' + content + ' 太复杂了，无法解析'


        if (content === '0') {
            reply = 'http://hjyvuessr.free.idcfengye.com\n' +
                    'http://www.myoli.xin'
        }
        // 对用户进行打标签
        else if (content === 'imooc') {
            const countData = await api.wechat.saveMPUser(message, 'imooc')
            const user = countData.user
            const count = countData.count
            let nickname = user.nickname

            if (user.gender === '1') {
                nickname = `小鲜肉 - ${nickname}`
            } else {
                nickname = `小姐姐 - ${nickname}`
            }

            let guess = '我猜不出你来自哪里,'

            if (user.province || user.city) {
                guess = `我猜你来自${user.province}省,${user.city}市`
            }

            let end = `${guess}哈哈，这些信息只有你关注，我才能从微信服务器里拿到，别紧张`

            reply = `你是来自慕课的${nickname},你有 ${count} 个来自慕课的小伙伴开始研究这个课程了,${end}`


        }
        else if (content === '1') {
            reply = 'oli吃大米'
        }
        else if (content === '2') {
            reply = 'oli吃葡桃'
        }
        else if (content === '3') {
            reply = 'oli吃桃子'
        }
        else if (content === 'imooc') {
            reply = '你是来自慕课的小伙伴'
        }
        else if (content === '4') {   // 回复临时图片

            // uploadMaterial方法名  image图片  路径
            let data = await client.handle('uploadMaterial', 'image', resolve(__dirname, '../1.jpg'))

            // console.log('回复图片',data)
            // { type: 'image',
            //     media_id: 'Y-SLJM5V92hM4jES5sK0lIzKz0UfzcshtDUZJRZKavt2CRliOesn4tVdv4Q2ddpY',
            //     created_at: 1539429303 }

            reply = {
                type: 'image',
                mediaId: data.media_id
            }
        }
        else if (content === '5') {   // 回复临时视频
            let data = await client.handle('uploadMaterial', 'video', resolve(__dirname, '../2.mp4'))
            // console.log('回复5', data)
            reply = {
                type: 'video',
                title: '回复视频（标题）',
                description: '回复视频（内容）',
                mediaId: data.media_id
            }
        }
        else if (content === '6') {   // 上传永久的视频
            let data = await client.handle('uploadMaterial', 'video', resolve(__dirname, '../4.mp4'), {
                type: 'video',
                description: '{"title": "这个地方很棒", "introduction": "好吃"}',
            })

            reply = {
                type: 'video',
                title: '回复的视频标题 2',
                description: '打个篮球玩玩',
                mediaId: data.media_id
            }
        }
        else if (content === '7') {   // 上传永久的图片
            let data = await client.handle('uploadMaterial', 'image', resolve(__dirname, '../11.jpg'), {
                type: 'image'
            })

            reply = {
                type: 'image',
                mediaId: data.media_id
            }
        }
        else if (content === '8') {   // 永久图文的上传
            let data = await client.handle('uploadMaterial', 'image', resolve(__dirname, '../1.jpg'), {
                type: 'image'
            })

            let data2 = await client.handle('uploadMaterial', 'pic', resolve(__dirname, '../11.jpg'), {
                type: 'image'
            })

            console.log('data===', data)

            let media = {
                articles: [
                    {
                        title: '这时服务端上传的图文1',
                        thumb_media_id: data.media_id,
                        author: 'hjy',
                        digest: '没有摘要',
                        show_cover_pic: 1,  // 是否出现封面图
                        content: '点击去往博客',
                        content_source_url: 'http://www.myoli.xin'
                    }, {
                        title: '这时服务端上传的图文222222',
                        thumb_media_id: data.media_id,
                        author: 'hjy2',
                        digest: '没有摘要2',
                        show_cover_pic: 1,  // 是否出现封面图
                        content: '点击去往另一个博客2',
                        content_source_url: 'http://vueblog.myoli.xin'
                    }
                ]
            }

            // 上传永久图文素材
            let uploadData = await client.handle('uploadMaterial', 'news', media, {})
            console.log('上传图文', uploadData)

            // let newMedia = {
            //     media_id: uploadData.media_id,
            //     index: 0,
            //     articles: {
            //         title: 'xxxx',
            //         thumb_media_id: data.media_id,
            //         author: 'hjy',
            //         digest: '没有摘要',
            //         show_cover_pic: 1,  // 是否出现封面图
            //         content: '点击去往博客',
            //         content_source_url: 'http://myoli.xin'
            //     }
            // }

            // 修改素材
            // let mediaData = await client.handle('updateMaterial', uploadData.media_id, newMedia)
            // console.log('mediaData', mediaData)

            // 获取永久素材
            let newsData = await client.handle('fetchMaterial', uploadData.media_id, 'news', true)
            let items = newsData.news_item
            let news = []

            console.log('items', items)
            items.forEach(item => {
                news.push({
                    title: item.title,
                    description: item.digest,// item.description
                    picUrl: data2.url,
                    url: item.url
                })
            })


            console.log('news===', news)

            reply = news
        }
        else if (content === '9') {   // 查看素材的总数
            let counts = await client.handle('countMaterial')
            console.log(JSON.stringify(counts))

            let res = await Promise.all([
                client.handle('batchMaterial', {
                    type: 'image',
                    offset: 0,
                    count: 10
                }),

                client.handle('batchMaterial', {
                    type: 'video',
                    offset: 0,
                    count: 10
                }),

                client.handle('batchMaterial', {
                    type: 'voice',
                    offset: 0,
                    count: 10
                }),

                client.handle('batchMaterial', {
                    type: 'news',
                    offset: 0,
                    count: 10
                }),
            ])

            console.log('res', res)

            reply = `
                image: ${res[0].total_count}
                video: ${res[1].total_count}
                voice: ${res[2].total_count}
                news: ${res[3].total_count}
              `
        }
        else if (content === '10') {  // 标签管理

            // 创建标签
            // let newTag = await client.handle('createTag', '朋友')
            // console.log('创建标签=', newTag)

            // 删除标签
            // await client.handle('delTag', 101)
            // 修改标签
            // await client.handle('updateTag', 100, '慕课网')

            // 获取标签下粉丝列表
            let userList1 = await client.handle('fetchTagUsers', 2)
            console.log('获取标签下粉丝列表1===', userList1)

            // 批量为用户打标签 false 或 取消标签 true
            await client.handle('batchTag', [message.FromUserName], 100, false)

            // 获取标签下粉丝列表
            let userList2 = await client.handle('fetchTagUsers', 100)
            console.log('获取标签下粉丝列表2===', userList2)

            // 查看标签总数
            let tagsData = await client.handle('fetchTags')
            console.log('查看标签总数=', tagsData)

            // 获取用户身上的标签列表
            // let userTags = await client.handle('getUserTags', message.FromUserName)
            // console.log('获取用户身上的标签列表=', userTags)

            reply = tagsData.tags.length
        }
        else if (content === '11') {  // 用户管理
            let userList = await client.handle('fetchUserList')

            console.log('userList', userList)

            reply = userList.total + ' 个关注者'
        }
        else if (content === '12') {  // 设置用户备注名
            let userList = await client.handle('remarkUser', message.FromUserName, 'hjy888')

            console.log('userList', userList)

            reply = '改名成功'
        }
        else if (content === '13') {  // 获取用户的详细信息
            let userInfoData = await client.handle('getUserInfo', message.FromUserName)

            console.log('userList', userInfoData)

            reply = JSON.stringify(userInfoData)
        }
        else if (content === '14') {  // 批量获取用户详细信息
            let batchUserInfo = await client.handle('fetchBatchUsers', [
                {
                    openid: message.FromUserName,
                    lang: 'zh_CN'
                }, {
                    openid: 'oaxz45lMwVFaGcynwxC3_i0pqCN8',
                    lang: 'zh_CN'
                }
            ])

            console.log('batchUserInfo', batchUserInfo)

            reply = JSON.stringify(batchUserInfo)
        }
        else if (content === '15') {  // 获取票据（也就是关注公众号的二维码）

            // 获取临时票据
            // let tempQrData = {
            //     expire_seconds: 400000,// 失效时间
            //     action_name: 'QR_SCENE',
            //     action_info: {
            //         scene: {
            //             scene_id: 101
            //         }
            //     }
            // }
            // let tempTicketData = await client.handle('createQrcode', tempQrData)
            //
            // console.log('tempTicketData', tempTicketData)
            //
            // // 不需要加await，本身是一个同步的方法
            // let tempQr = client.showQrcode(tempTicketData.ticket)
            // reply = tempQr.rul


            // 获取永久票据（有数量限制）
            let qrData = {
                action_name: 'QR_SCENE',
                action_info: {
                    scene: {
                        scene_id: 99
                    }
                }
            }
            let ticketData = await client.handle('createQrcode', qrData)

            console.log('tempTicketData', ticketData)

            // 不需要加await，本身是一个同步的方法
            let qr = client.showQrcode(ticketData.ticket)

            console.log('qr', qr)

            reply = qr
        }
        else if (content === '16') {      // 长链接转短链接
            let longurl = 'http://myoli.xin?a=1'
            let shortData = await client.handle('createShortUrl', 'long2short', longurl)

            console.log('shortData', shortData)

            reply = shortData.short_url
        }
        else if (content === '17') {      // 语义理解（查询特定的语句进行分析）
            let semanticData = {
                query: '查一下明天从北京到上海的南航机票',
                city: '北京',
                category: 'flight,hotel',
                uid: message.FromUserName
            }
            let searchData = await client.handle('semantic', semanticData)

            console.log('searchData', searchData)

            reply = JSON.stringify(searchData)
        }
        else if (content === '18') {      // ai（中文转英文）
            let body = '编程语言难学么'
            let aiData = await client.handle('aiTranslate', body, 'zh_CN', 'en_US')

            console.log('aiData', aiData)

            reply = JSON.stringify(aiData)
        }
        else if (content === '19') {      // 创建菜单、删除菜单
            try{
                // 删除老菜单
                let deleteMenu = await client.handle('deleteMenu')
                console.log('deleteMenu', deleteMenu)

                let menu = {
                    button: [
                        {
                            name: '一级菜单',
                            sub_button: [
                                {
                                    name: '二级菜单 1',
                                    type: 'click',
                                    key: 'no_1'
                                }, {
                                    name: '二级菜单 2',
                                    type: 'click',
                                    key: 'no_2'
                                }, {
                                    name: '二级菜单 3',
                                    type: 'click',
                                    key: 'no_3'
                                }, {
                                    name: '二级菜单 4',
                                    type: 'click',
                                    key: 'no_4'
                                }, {
                                    name: '二级菜单 5',
                                    type: 'click',
                                    key: 'no_5'
                                }
                            ]
                        },
                        {
                            name: '分类',
                            type: 'view',
                            url: 'https://www.imooc.com'
                        },
                        {
                            name: '新菜单_' + Math.random(),
                            type: 'click',
                            key: 'new_111'
                        }
                    ]
                }

                // 创建新菜单
                let createData = await client.handle('createMenu', menu)
                console.log('createData', createData)
            } catch (e) {
                console.log(e)
            }

            reply = '菜单创建成功，请等5分钟，或者先取消关注，再重新关注'
        }
        else if (content === '20') {      // 微信自带功能（例如：点击跳转到外链、拍照等）
            try{
                // 删除老菜单
                let deleteMenu = await client.handle('deleteMenu')
                console.log('deleteMenu', deleteMenu)

                let menu = {
                    button: [
                        {
                            name: '发图扫码',
                            sub_button: [
                                {
                                    name: '系统拍照',
                                    type: 'pic_sysphoto',
                                    key: 'no_1'
                                }, {
                                    name: '拍照或者发图',
                                    type: 'pic_photo_or_album',
                                    key: 'no_2'
                                }, {
                                    name: '微信相册发布',
                                    type: 'pic_weixin',
                                    key: 'no_3'
                                }, {
                                    name: '扫码',
                                    type: 'scancode_push',
                                    key: 'no_4'
                                }, {
                                    name: '等待中扫码',
                                    type: 'scancode_waitmsg',
                                    key: 'no_5'
                                }
                            ]
                        },
                        {
                            name: '跳新链接',
                            type: 'view',
                            url: 'https://www.imooc.com'
                        },
                        {
                            name: '其他',
                            sub_button: [
                                {
                                    name: '点击',
                                    type: 'click',
                                    key: 'new_11'
                                }, {
                                    name: '地理位置',
                                    type: 'location_select',
                                    key: 'new_12'
                                }
                            ]
                        }
                    ]
                }

                // 创建新菜单
                let createData = await client.handle('createMenu', menu)
                console.log('createData', createData)
            } catch (e) {
                console.log(e)
            }

            reply = '菜单创建成功，请等5分钟，或者先取消关注，再重新关注'
        }
        else if (content === '20-1') {      // 自定义菜单（千人千面：也就是不同人看到的菜单是不同的）
            try{
                let menu = {
                    button: [
                        {
                            // 文案不同
                            name: 'Scan_Photo',
                            sub_button: [
                                {
                                    name: '系统拍照',
                                    type: 'pic_sysphoto',
                                    key: 'no_1'
                                }, {
                                    name: '拍照或者发图',
                                    type: 'pic_photo_or_album',
                                    key: 'no_2'
                                }, {
                                    name: '微信相册发布',
                                    type: 'pic_weixin',
                                    key: 'no_3'
                                }, {
                                    name: '扫码',
                                    type: 'scancode_push',
                                    key: 'no_4'
                                }, {
                                    name: '等待中扫码',
                                    type: 'scancode_waitmsg',
                                    key: 'no_5'
                                }
                            ]
                        },
                        {
                            name: '跳新链接',
                            type: 'view',
                            url: 'https://www.imooc.com'
                        },
                        {
                            name: '其他',
                            sub_button: [
                                {
                                    name: '点击',
                                    type: 'click',
                                    key: 'new_11'
                                }, {
                                    name: '地理位置',
                                    type: 'location_select',
                                    key: 'new_12'
                                }
                            ]
                        }
                    ]
                }

                let rules = {
                    // tag_id: '2',
                    // sex: '1',
                    // country: '中国',
                    // province: '广东',
                    // city: '广州',
                    // client_platform_type: '2',   // 操作系统
                    language: 'en'
                }

                // 创建新菜单
                let createData = await client.handle('createMenu', menu, rules)
                console.log('createData', createData)
            } catch (e) {
                console.log(e)
            }

            // 获取菜单
            let menu = await client.handle('fetchMenu')
            console.log('menu=', JSON.stringify(menu))


            reply = '菜单创建成功，请等5分钟，或者先取消关注，再重新关注'
        }
        else if (content === '更新菜单') {
            try{
                // 删除老菜单
                let deleteMenu = await client.handle('deleteMenu')

                // 创建新菜单
                let createData = await client.handle('createMenu', commonMenu)
            } catch (e) {
            }

            reply = '菜单创建成功，请等5分钟，或者先取消关注，再重新关注'
        }
        else if (content === '首页') {
            reply = [{
                title: '时光的预热',
                description: '匆匆岁月',
                picUrl: 'http://img2.mukewang.com/5abe468b0001664107390741-160-160.jpg',
                url: config.baseUrl
            }]
        }
        else {
            let movies = await api.movie.searchByKeyword(content)
            reply = []

            if (!movies || movies.length === 0) {
                let catData = await api.movie.findMoviesByCat(content)
                if (catData) {
                    movies = catData.movies
                }
            }

            if (!movies || movies.length === 0) {
                movies = await api.movie.searchByDouban(content)
            }

            if (!movies || movies.length) {
                reply = []
                movies = movies.splice(0, 4)

                movies.forEach(movie => {
                    reply.push({
                        title: movie.title,
                        description: movie.title,
                        picUrl: 'http://img2.mukewang.com/5abe468b0001664107390741-160-160.jpg',
                        url: config.baseUrl + '/movie/' + movie._id
                    })
                })
            } else {
                reply = '没有查询到与 ' + content + ' 相关的电影，换个名字试试'
            }

            // console.log('reply===', reply)
        }

        ctx.body = reply
    }

    await next()
}